// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  if (event.action && infoHelper[event.action]) {
    const result = await infoHelper[event.action](wxContext, event)
    return result
  }

  return {
    message: 'This action was not found',
    error: -1,
  }
}

//数据库
const db = cloud.database()
const info = db.collection("solitaire")
const _ = db.command
const $ = _.aggregate
const infoHelper = {
  //创建
  async create(context, params) {
    params.data._openid = context.OPENID
    params.data.date = db.serverDate()
    params.data.num = 0
    return await info.add({
      data: params.data
    })
  },
  //更新人数
  async updateNum(context, params) {
    return await info.doc(params.data._id).update({
     data:{
      num: _.inc(1)
     }
    })
  },
  //获取活动列表
  async getSolitaireList(context, params) {
    const aggregate = info.aggregate().match({
      _openid: context.OPENID //活动列表只看自己
    })
    return await _lookup(aggregate, context.OPENID)
      // .skip(params.data.skip)
      // .limit(params.data.limit)
      .end()
  },

  //删除活动
  async delSolitaire(context, params) {
    return await info.doc(params.data._id).remove()
  },
  //获取指定活动
  async getSolitaireById(context, params) {
    const aggregate = info.aggregate().match({
      _id: params.data._id //详情页面
    })
    return await _lookup(aggregate, context.OPENID).end()
  },
}

function _lookup(aggregate, _openid) {
  return aggregate
    .lookup({
      from: 'users',
      localField: '_openid',
      foreignField: '_openid',
      as: 'users'
    })
    .lookup({
      from: 'solitaire-activity',
      localField: 'activity',
      foreignField: 'type',
      as: 'activity'
    })
    .project({
      activity: $.arrayElemAt(['$activity', 0]),
      remarks: 1,
      title: 1,
      date: 1,
      num: 1,
      user: $.arrayElemAt(['$users', 0]),
    })
    .project({
      user: $.mergeObjects(['$user.userInfo', '$user']),
      remarks: 1,
      title: 1,
      date: 1,
      num: 1,
      activity: 1,
    })
    .project({
      user: {
        avatarUrl: 1,
        nickName: 1,
        isSelf: $.eq(['$user._openid', _openid])

      },
      remarks: 1,
      title: 1,
      date: 1,
      num: 1,
      activity: {
        name: 1,
        color: 1
      },
    })
}